//
//  TextmasterAppDelegate.m
//  Textmaster
//
//  Created by Anshu Chimala on 12/31/09.
//  Copyright 2009 Home. All rights reserved.
//

#import "TextmasterAppDelegate.h"
#import "TMPreferences.h"
#import <Sparkle/Sparkle.h>

@implementation TextmasterAppDelegate
@synthesize window = _window;
@synthesize searchField = _searchField;

OSStatus toggleHidden(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) {
	TextmasterAppDelegate *delegate = (TextmasterAppDelegate *)[NSApp delegate];
	id window = [delegate window];
	id animator = [window animator];
	
	if([animator isVisible] && [window isKeyWindow])
		[window orderOut:nil];
	else {
		[NSApp activateIgnoringOtherApps:YES];
		[window makeKeyAndOrderFront:nil];
		
		NSSearchField *search = [delegate searchField];
		[search setStringValue:@""];
		[window makeFirstResponder:search];
		
		// Curiouser and curiouser.
		// (This is a somewhat ugly workaround to get the search results to clear
		// when the user reloads the app).
		[[NSNotificationCenter defaultCenter] postNotificationName:@"becameVisible" object:nil];
	}
	return noErr;
}

- (void)toggleHidden {
	toggleHidden(nil,nil,nil);
}

- (void)setKeyCombo:(KeyCombo)newKeyCombo {
	_shortcut = newKeyCombo;
	[self synchronizeShortcut];
}

- (void)synchronizeShortcut {
	UnregisterEventHotKey(_hotkeyRef);
	int modifiers = 0;
	if(_shortcut.flags & NSControlKeyMask)
		modifiers += controlKey;
	if(_shortcut.flags & NSAlternateKeyMask)
		modifiers += optionKey;
	if(_shortcut.flags & NSCommandKeyMask)
		modifiers += cmdKey;
	if(_shortcut.flags & NSShiftKeyMask)
		modifiers += shiftKey;
	RegisterEventHotKey(_shortcut.code, modifiers, _hotkeyID, GetApplicationEventTarget(), 0, &_hotkeyRef);
	
	[TMPreferences setShortcutKeyCombo:_shortcut];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	_shortcut = [TMPreferences shortcutKeyCombo];
	if(_shortcut.code == 0 && _shortcut.flags == 0) {
		_shortcut.code = 0x9;
		_shortcut.flags |= NSShiftKeyMask;
		_shortcut.flags |= NSAlternateKeyMask;
		
		// Option + Shift + V is the default keycode
	}
	
	_eventType.eventClass=kEventClassKeyboard;
	_eventType.eventKind=kEventHotKeyPressed;	
	InstallApplicationEventHandler(&toggleHidden,1,&_eventType,NULL,NULL);
	_hotkeyID.signature='htk1';
	_hotkeyID.id=1;
	int modifiers = 0;
	if(_shortcut.flags & NSControlKeyMask)
		modifiers += controlKey;
	if(_shortcut.flags & NSAlternateKeyMask)
		modifiers += optionKey;
	if(_shortcut.flags & NSCommandKeyMask)
		modifiers += cmdKey;
	if(_shortcut.flags & NSShiftKeyMask)
		modifiers += shiftKey;
	RegisterEventHotKey(_shortcut.code, modifiers, _hotkeyID, GetApplicationEventTarget(), 0, &_hotkeyRef);
}

- (void)dealloc {
	self.window = nil;
	[super dealloc];
}

@end
